package com.scut.edu.wanyou;

import com.scut.edu.wanyou.util.UserKeeper;
import com.scut.edu.wanyou.util.UserToken;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.keep.AccessTokenKeeper;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.Toast;

public class SplashActivity extends Activity {
	
	private Oauth2AccessToken accessToken = null;
	
	private UserToken userToken = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		getWindow().setBackgroundDrawable(
				getResources().getDrawable(R.drawable.splash_load));
		
		handler.postDelayed(initTasks, 2000);
	}
	
	private boolean isNetworkConnected()
	{
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if(networkInfo!=null)
		{
			return networkInfo.isAvailable();
		}
		return false;
	}
	
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Intent intent = null;
			switch (msg.what) {
			case 0:
				if((userToken!=null&&userToken.isValid())||(accessToken!=null&&accessToken.isSessionValid()))
				{
					intent = new Intent(SplashActivity.this,MainActivity.class);
				}else {
					intent = new Intent(SplashActivity.this,InitActivity.class);
				}
				startActivity(intent);
				finish();
				break;
			default:
				break;
			}
			
		}
		
	};
	
private Runnable initTasks = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(!isNetworkConnected())
			{
				Toast.makeText(getApplicationContext(), "网络连接发生错误!请检查", Toast.LENGTH_SHORT).show();
			}
			accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
			userToken = UserKeeper.readUserToken(getApplicationContext());
			handler.obtainMessage(0).sendToTarget();
		}
	};
	

}
